﻿using System;

namespace Shared.Service.Domain.CommonUtility
{
    public static class FormatConvert
    {
        public static DateTime? StringToDatetime(string dateTimeStr)
        {
            DateTime.TryParse(dateTimeStr, out DateTime dateTime);
            return dateTime.Equals(DateTime.MinValue) ? (DateTime?)null : dateTime;
        }

        public static string DatetimeToString(DateTime? dateTime) => dateTime.HasValue ? dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty;

        public static DateTime StringToDatetime2(string dateTimeStr)
        {
            DateTime.TryParse(dateTimeStr, out DateTime dateTime);
            return dateTime;
        }

        /// <summary>
        /// 获取当前Unix时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetUnixTimestamp(DateTime time) => (long)time.Subtract(TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local)).TotalSeconds;

        /// <summary>
        /// Unix时间戳转为时间
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        public static DateTime UnixTimestampToDatetime(long timestamp)
        {
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        public static long StringToLong(string str)
        {
            if (long.TryParse(str, out var num))
            {
                return num;
            }

            return 0;
        }        
    }
}
